package OrderService

import (
	"context"
	"database/sql"
	"gdshop-font-api-go/app/entity"
	"gdshop-font-api-go/app/request/OrderReq"
	"gdshop-font-api-go/app/response/OrderResp"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/frame/g"
)

// 用户关闭订单 判断状态，必须是 1待付款 才可以关闭订单
func OrderSubAftersale(ctx context.Context, parames *OrderReq.OrderSubAftersale) *response.JsonResponse {
	var osModel OrderResp.SubOrder
	err := db.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").Where("id", parames.Sid).
		Struct(&osModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if !IsMyOrder(ctx, osModel.OrderId, int(parames.MemberId)) {
		return response.FailByRequestMessage(nil, "请勿操作别人的订单")
	}

	var orList []*entity.OrderRefund
	err = db.GetUnSafaTable(ctx, "order_refund").
		FieldsEx("create_at", "update_at", "delete_at").
		Where("order_sub_id", parames.Sid).
		Structs(&orList)
	if err != nil {
		if err != sql.ErrNoRows {
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	goodsStatus := g.List{}
	goodsStatus = append(goodsStatus, g.Map{
		"text": "未收到货",
		"id":   1,
	})
	goodsStatus = append(goodsStatus, g.Map{
		"text": "已收到货",
		"id":   2,
	})
	reasonType := g.List{}
	reasonType = append(reasonType, g.Map{
		"text": "不喜欢/不想要",
		"id":   1,
	})
	reasonType = append(reasonType, g.Map{
		"text": "空包裹",
		"id":   2,
	})
	reasonType = append(reasonType, g.Map{
		"text": "未按约定发货",
		"id":   3,
	})
	reasonType = append(reasonType, g.Map{
		"text": "快递/物流一直未找到",
		"id":   4,
	})
	status := g.List{}
	status = append(status, g.Map{
		"text": "待处理",
		"id":   1,
	})
	status = append(status, g.Map{
		"text": "拒绝",
		"id":   2,
	})
	status = append(status, g.Map{
		"text": "同意",
		"id":   3,
	})
	status = append(status, g.Map{
		"text": "退款完成",
		"id":   99,
	})

	jieguo := g.Map{
		"order":          osModel,
		"photo_base_url": g.Cfg().GetString("site.PhotoUrlProfix"),
		"goods_status":   goodsStatus,
		"reason_type":    reasonType,
		"status":         status,
	}

	if orList == nil {
		jieguo["refunds"] = []string{}
	} else {
		jieguo["refunds"] = orList
	}

	return response.SuccessByRequestMessageData(nil, "成功", jieguo)
}
